<script setup>
import util from '@/utils/util'
import {Dict} from '@/utils/resource'
import {showSaveResponse, validateForm, validFieldExists} from '@/utils/element-helper'
import {reactive, ref} from "vue";
import {useRouter} from "vue-router";
import {ElMessage} from "element-plus";
import {commonStore} from "@/store/common";

const router = useRouter()
const commonS = commonStore()
const props = defineProps({
  code: {
    type: String,
    default: ""
  },
})
const form = ref(null)
const isNew = props.code === 'new'
const code = props.code

const state = reactive({
  loading: false,
  isNew: true,
  initForm: [],
  attributes: [],
  form: {},
  rules: {
    code: [
      {required: true, message: '编码不能为空', trigger: 'blur'},
      {
        validator: (rule, value, callback) => {
          validFieldExists(rule, value, callback, state.initForm[rule.field] !== value || isNew, (rule, value) => Dict.exists(rule, value))
        }, trigger: 'blur'
      }
    ],
    description: [
      {required: true, message: '描述不能为空', trigger: 'blur'},
    ],
  },
})

if (!isNew) {
  loadDict()
} else {
  state.attributes = [{
    type: 1
  }]
}

async function loadDict() {
  let res = await Dict.listByCode(code)

  state.attributes = res.data.map(data => ({
    key: data.key,
    value: data.value,
    priority: data.priority,
    comment: data.comment,
    error: ""
  })).concat({
    type: 1
  })
  state.form = {
    id: res.data[0].id,
    code: res.data[0].code,
    description: res.data[0].description
  }
  state.initForm = util.copy(state.form)
}

function handleDelete(index, row) {
  //删除
  state.attributes.splice(index, 1)
}

function handleAdd(index, row) {
  row.type = 0
  state.attributes.push({
    type: 1
  })
}

function submitForm(formName) {
  return validateForm(form.value, formName, () => {
    let attrs = []
    for (let i = 0; i < state.attributes.length; i++) {
      let atttrbute = state.attributes[i]
      if (atttrbute.type !== 1) {
        if (util.isNull(atttrbute.key)) {
          ElMessage({
            type: 'error',
            message: '字典属性名不能为空！'
          })
          return
        }
        if (util.isNull(atttrbute.value)) {
          ElMessage({
            type: 'error',
            message: '字典属性值不能为空！'
          })
          return
        }
        attrs.push(state.attributes[i])
      }
    }
    if (attrs.length === 0) {
      ElMessage({
        type: 'error',
        message: '字典值至少包含一条数据！'
      })
      return
    }
    state.form.attributes = attrs
    showSaveResponse(state.loading, () => Dict.updateWithAttribute(state.form), (res) => {
      commonS.loadDict(state.form.code)
      return router.back();
    })
  })
}
</script>

<template>
  <div>
    <div style="padding-left: 20px">
      <p style="font-size: 20px">字典</p>
      <el-form :model="state.form" label-position="left" :rules="state.rules" ref="form" label-width="140px"
               class="dict-form">
        <el-form-item label="编码" prop="code" class="my-form-item">
          <el-input v-model="state.form.code" :disabled="!isNew"></el-input>
        </el-form-item>
        <el-form-item label="描述" prop="description" class="my-form-item">
          <el-input v-model="state.form.description"></el-input>
        </el-form-item>
        <p style="color: #606266">字典值</p>
        <el-table v-loading="state.loading"
                  :data="state.attributes"
                  stripe
                  :show-header="false"
                  style="width: 100%">
          <el-table-column type="expand">
            <template #default="scope">
              <el-form-item v-if="scope.row.type !== 1" label="字典描述" label-width="70px" prop="comment">
                <el-input v-model="scope.row.comment" type="textarea"></el-input>
              </el-form-item>
            </template>
          </el-table-column>
          <el-table-column
              prop=""
              label="属性名">
            <template #default="scope">
              <el-form-item v-if="scope.row.type !== 1" label="属性名" label-width="70px" prop="key">
                <el-input v-model="scope.row.key" style="width: 100px;"></el-input>
              </el-form-item>
            </template>
          </el-table-column>
          <el-table-column
              prop=""
              label="属性值">
            <template #default="scope">
              <el-form-item v-if="scope.row.type !== 1" label="属性值" prop="value" label-width="70px">
                <el-input v-model="scope.row.value" style="min-width: 180px;"></el-input>
              </el-form-item>
            </template>
          </el-table-column>
          <el-table-column
              prop="priority"
              label="排序"
              width="140">
            <template #default="scope">
              <el-form-item v-if="scope.row.type !== 1" label="排序" prop="priority" label-width="50px">
                <el-input v-model="scope.row.priority" type="number"></el-input>
              </el-form-item>
            </template>
          </el-table-column>
          <el-table-column
              prop=""
              align="center"
              label="操作"
              min-width="50">
            <template #default="scope">
              <el-button v-if="scope.row.type !== 1"
                         type="danger"
                         size="small"
                         icon="Delete"
                         @click="handleDelete(scope.$index, scope.row)">删除</el-button>
              <el-button v-else
                         type="success"
                         size="small"
                         icon="Plus"
                         @click="handleAdd(scope.$index, scope.row)">新增</el-button>
            </template>
          </el-table-column>
        </el-table>
      </el-form>
    </div>
  </div>
  <div style="padding: 15px">
    <router-link to="/dict">
      <el-button plain round type="info" icon="Back" style="margin-right: 10px;">返回</el-button>
    </router-link>
    <el-button plain type="primary" icon="CircleCheck" @click="submitForm('form')">保存</el-button>
  </div>
</template>


<!-- Add "scoped" attribute to limit CSS to this component only -->
<style scoped>
.dict-form {
  width: 100%;
}

.my-form-item {
  max-width: 600px;
  margin-bottom: 25px;
}
</style>
